<template>
  <nut-infinite-loading v-model="state.upRefresh" :has-more="!state.finished" @load-more="onLoad">
    <nut-pull-refresh v-model="state.dropRefresh" @refresh="onRefresh">
      <slot />
    </nut-pull-refresh>
  </nut-infinite-loading>
</template>
<script setup name="freshLoad">
import {onMounted, reactive, ref} from "vue";
import tool from "@/utils/tool.js";
const props = defineProps({
  searchModel: {type: Object, default: () => {}},
  url: {type: String, default: ''},
  allowLoading: {type: Boolean, default: true}
})
const state = reactive({
	upRefresh: false,
	dropRefresh: false,
  finished: false,
  hasMore: true,
})
const currentPage = ref(1)
const pageSize = ref(30)
const total = ref(0)
const emit = defineEmits(['action', 'getList'])
const list = ref([])
const onLoad = () => {
	getList(state)
}
const onRefresh = () => {
	state.finished = false
  getList(state)
}
onMounted(() => {
  getList()
})
const getList = (states) => {

  if (states) {
    if(states.upRefresh) {
      currentPage.value = currentPage.value + 1
    }
    if(states.dropRefresh) {
      currentPage.value = 1
    }
  }
  else {
    currentPage.value = 1
  }
  let obj = {currentPage: currentPage.value, pageSize: pageSize.value}
  obj = Object.assign(obj, props.searchModel)
  tool.post(props.url, obj, props.allowLoading).then(ret => {
    if(ret.stat) {
      emit('getList', ret.data)
      if(states) {
        if(states.upRefresh) {
          states.upRefresh = false
          if(ret.data.list.length === 0) states.finished = true
          for (let i = 0; i < ret.data.list.length; i++) {
            list.value.push(ret.data.list[i])
          }
        }
        if(ret.data.list.length === 0) states.finished = true
        if(states.dropRefresh) {
          states.dropRefresh = false
          list.value = []
          for (let i = 0; i < ret.data.list.length; i++) {
            list.value.push(ret.data.list[i])
          }
        }
      }
      else {
        list.value = []
        for (let i = 0; i < ret.data.list.length; i++) {
          list.value.push(ret.data.list[i])
        }
        total.value = ret.data.total
        // if(list.value.length < pageSize.value) state.finished = true
      }
      emit('action', list.value)
    }
  })
}

defineExpose({getList})
</script>
